<?php

namespace app\admin\service;

use support\spark\exception\ApiException;
use support\spark\model\goods\GoodsAttrTpl;

class GoodsAttrService
{

    /**
     * 获取商品属性列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['name'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $goodsAttrTplModel = new GoodsAttrTpl();
        $list = $goodsAttrTplModel->getPaginateList($where, ['*'], ['id' => 'desc'], [], $limit);
        foreach ($list['data'] as $key => $item) {
            $list['data'][$key]['attr'] = json_decode($item['value'], true);
        }
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加商品属性
     * @param $param
     * @return array
     */
    public function addGoodsAttr($param)
    {
        $name = $param['name'];
        unset($param['name']);

        $goodsAttrTplModel = new GoodsAttrTpl();
        $has = $goodsAttrTplModel->checkUnique([
            'name' => $name
        ]);

        if (!empty($has)) {
            throw new ApiException('该模板名称已经存在', -1);
        }
        $addParam['name'] = $name;
        $addParam['value'] = json_encode($param);
        $addParam['create_time'] = now();
        $addParam['update_time'] = now();
        $goodsAttrTplModel->insertOne($addParam);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑商品属性
     * @param $param
     * @return array
     */
    public function editGoodsAttr($param)
    {
        $name = $param['name'];
        $id = $param['id'];
        unset($param['name'], $param['id']);
        $goodsAttrTplModel = new GoodsAttrTpl();
        $where[] = ['id', '<>', $id];
        $where[] = ['name', '=', $name];
        $has = $goodsAttrTplModel->checkUnique($where);
        if (!empty($has)) {
            throw new ApiException('该模板名称已经存在', -1);
        }

        $editParam['name'] = $name;
        $editParam['value'] = json_encode($param);
        $goodsAttrTplModel->updateById($editParam, $id);
        return dataReturn(0, '修改成功');
    }
}